/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 *
 * The Initial Developer of the Original Code is iSQL-Viewer, A Mutli-Platform Database Tool.
 * Portions created by Mark A. Kobold are Copyright (C) 2000-2007. All Rights Reserved.
 *
 * Contributor(s): 
 *  Mark A. Kobold [mkobold <at> isqlviewer <dot> com].
 *  
 * If you didn't download this code from the following link, you should check
 * if you aren't using an obsolete version: http://www.isqlviewer.com
 */
package org.isqlviewer.swing.table;

import java.util.Comparator;
import java.util.List;

/**
 * Utility class for sortings collections.
 * <p>
 * This class was designed mainly for use within the EnhancedTableModel and the Sortable Interface.
 * 
 * @author Mark A. Kobold &lt;mkobold at isqlviewer dot com&gt;
 * @version 1.0
 */
class RowComparator implements Comparator<List<Object>> {

    private int cColumn = 0;
    private boolean isAscending = true;

    /**
     * Default constructor for a given colum and direction.
     * <p>
     * Once the compare method is called it will use the comparable column as the index of the List Object it is
     * comparing. The isAsc variable allows for easy ascending and desceding sorting.
     * 
     * @param comparableColumn index to compare from.
     * @param isAsc boolean to multiply the comparable value by -1 to reverse its comparsion.
     */
    public RowComparator(int comparableColumn, boolean isAsc) {

        cColumn = comparableColumn;
        isAscending = isAsc;
    }

    /**
     * Compares objects within the list as specified by the Comparable interface.
     * <p>
     * 
     * @see Comparable#compareTo(java.lang.Object)
     * @param src instance of List to compare.
     * @param cmp instance of List to compare.
     */
    public int compare(List<Object> src, List<Object> cmp) {

        if (cColumn == -1) {
            return 0;
        }

        Object s = src.get(cColumn);
        Object c = cmp.get(cColumn);
        if (s == null & c != null) {
            return (isAscending ? -1 : 1) * -1;
        } else if (s != null & c == null) {
            return (isAscending ? -1 : 1) * 1;
        } else if (s == null && c == null) {
            return 0;
        } else if (s instanceof Comparable) {
            Comparable cs = (Comparable) s;
            return (isAscending ? -1 : 1) * cs.compareTo(c);
        }
        return 0;
    }

}